package factory;

import factory.dao.IProductDao;
import factory.dao.IUserDao;
import factory.dao.impl.ProductDaoImpl;
import factory.dao.impl.UserDaoImpl;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class DaoFactory {

    private static Map<String, Object> cacheMap = new HashMap<>();

    /*** 构造器私有化*/
    private DaoFactory() {
    }

    //不需要外部进行访问
    private static Properties pros = new Properties();

    // 在静态代码块中加载
    static {
        try {
            pros.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("factory/config/dao.properties"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static <T> T createDao(String daoName) {
        //根据key拿到相应value，创建这个类的全限定名称
        String className = pros.getProperty(daoName);
        //拿到全限名，根据反射创建对象
        try {
            T t = (T) cacheMap.get(daoName);
            if (t == null) {
                Class<?> clz = Class.forName(className);
                t = (T) clz.newInstance();
                //把对象放到缓存里面去
                cacheMap.put(daoName, t);
            }
            return t;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        IProductDao productDao = DaoFactory.createDao("productDao");
        System.out.println(productDao);
        IProductDao userDao = DaoFactory.createDao("productDao");
        System.out.println(userDao);

        System.out.println(productDao==userDao);
    }
}
